import config from '../../config';
import { gameStart, gamePoll } from '../../api/index';

Page({
  data: {
    imgPrefix: config.IMG_PREFIX,
    room: {},
    percent: 0,
    game: {
      current_num: 0,
      going_users: [
        // {
        //   headimgurl: 'http://placehold.it/100x100',
        //   nickname: 'adadadadadasdadasdasdadadadadadasda'
        // }
      ],
      status: 'waiting',
      total_num: 50
    }
  },

  onLoad() {
    gameStart({
      success: res => {
        let room = res.data.data;
        this.setData({
          room
        });
        this.poll(room.roomid);
      }
    });
  },

  poll(roomid) {
    gamePoll({
      data: {
        roomid
      },
      success: res => {
        let game = res.data.data;

        if (game.status === 'answering') {
          wx.redirectTo({
            url: '/pages/game/game?roomid=' + roomid
          });
          return;
        }

        if (game.status === 'waiting') {
          this.setData({
            percent: Math.floor((game.current_num / game.total_num) * 100),
            game
          });
          setTimeout(() => {
            this.poll(roomid);
          }, 1000);
        }
      }
    });
  }
});
